package com.mlink.vs.action;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.seasar.struts.annotation.Execute;

import com.google.gson.Gson;
import com.mlink.vs.entity.PiccUser;
import com.mlink.vs.entity.PiccUserOnlineStatus;
import com.mlink.vs.entity.UCResult;
import com.mlink.vs.service.DbTimeService;
import com.mlink.vs.service.PiccSeatStatusService;
import com.mlink.vs.service.PiccUserOnlineStatusService;
import com.mlink.vs.service.PiccUserService;
import com.mlink.vs.sso.BaseAction;
import com.mlink.vs.util.Constants;
import com.mlink.vs.util.StreamUtil;

/**
 * 用户登陆接口
 * 
 * @author Administrator
 */
public class LoginAction {

	/**
	 * request请求对象
	 */
	@Resource
	private HttpServletRequest req;

	/**
	 * response请求对象
	 */
	@Resource
	private HttpServletResponse rep;

	@Resource
	PiccUserService piccUserService;
	@Resource
	PiccUserOnlineStatusService piccUserOnlineStatusService;
	@Resource
	PiccSeatStatusService piccSeatStatusService;

	@Resource
	DbTimeService dbTimeService;



	@Execute(validator = false)
	public String index() {

		Gson gson = new Gson();
		StringBuffer indata = StreamUtil.getRequestBody(req);
		Map<String, String> stsMap = new HashMap<String, String>();

		Map<String, String> mapData = gson.fromJson(indata.toString(), Map.class);
		if (mapData == null)
			return null;

		String uid = (String) mapData.get("uid");
		String passwd = (String) mapData.get("passwd");
		String type = (String) mapData.get("type"); // 设备类型。 前端写死，

		try {
			rep.setCharacterEncoding("utf-8");
			if (StringUtils.isBlank(uid)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "uid不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}

			if (StringUtils.isBlank(passwd)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "passwd不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}
			if (StringUtils.isBlank(type)) {
				stsMap.put("sts", "1");
				stsMap.put("type", "type不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}

			JSONObject body = new JSONObject();
			UCResult resuelt = null;

			body.put("uname", uid);
			body.put("passwd", passwd);
			body.put("type", type);
			resuelt = BaseAction.requeryUC("UAC_USER_AUTH", body);
			if (resuelt.code.equals("1")) {
				String token = resuelt.body.getString("TOKEN"); // 1 成功
				System.out.println("token=" + token);
				String userName = resuelt.body.getJSONObject("user").getString("truename");
				String userContact = resuelt.body.getJSONObject("user").getString("phone");
				String usertype = resuelt.body.getJSONObject("user").getString("role");
				String userCompany = resuelt.body.getJSONObject("user").getString("userCompany");

				String groupID = resuelt.body.getJSONObject("user").getString("groupID"); // groupname 对应 groupid
				String groupName = resuelt.body.getJSONObject("user").getString("orgName");  //  groupTrueName 对应 groupname
				
				
				// 设置在线
				PiccUserOnlineStatus piccUserOnlineStatus = new PiccUserOnlineStatus();
				piccUserOnlineStatus.userId = uid;
				piccUserOnlineStatus.isOnline = "1";
				piccUserOnlineStatus.userType = usertype;
				piccUserOnlineStatus.groupId = groupID;
				piccUserOnlineStatus.updateTime = dbTimeService.getDbTimeStamp();
				if (piccUserOnlineStatusService.isExist(uid) == true) {
					piccUserOnlineStatusService.updateStatusu(piccUserOnlineStatus);
				} else {
					piccUserOnlineStatusService.insert(piccUserOnlineStatus);
				}
				stsMap.put("sts", "0");
				stsMap.put("token", token);
				stsMap.put("userName", userName);
				stsMap.put("userContact", userContact);
				stsMap.put("usertype", usertype);
				stsMap.put("group", groupID);
				stsMap.put("userCompany", userCompany);
				stsMap.put("userId",uid);
				stsMap.put("groupName",groupName);
			
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			} else {
				stsMap.put("sts", "1");
				stsMap.put("msg", "uc 服务器异常 错误码：" + resuelt.code);
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}

		} catch (Exception e) {
			e.printStackTrace();
			stsMap.put("sts", "1");
			stsMap.put("msg", "uc 服务器异常");
			try {
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}

		return null;
	}

	@Execute(validator = false)
	public String logOut() {

		Gson gson = new Gson();
		StringBuffer indata = StreamUtil.getRequestBody(req);
		Map<String, String> stsMap = new HashMap<String, String>();

		Map<String, String> mapData = gson.fromJson(indata.toString(), Map.class);
		if (mapData == null)
			return null;

		if (BaseAction.checkToken(indata, rep) == false)
			return null; // 验证token是否有效 无效直接返回错误码-1000

		String uid = (String) mapData.get("uid");
		String TOKEN = (String) mapData.get("token");

		try {
			rep.setCharacterEncoding("utf-8");
			if (StringUtils.isBlank(uid)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "uid不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}

			if (StringUtils.isBlank(TOKEN)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "TOKEN不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}

			JSONObject body = new JSONObject();
			UCResult resuelt = null;

			body.put("TOKEN", TOKEN);
			body.put("userid", uid);
			resuelt = BaseAction.requeryUC("UAC_USER_LOGOUT", body);
			if (resuelt.code.equals("1")) {
				// 设置在线
				PiccUserOnlineStatus piccUserOnlineStatus = new PiccUserOnlineStatus();
				piccUserOnlineStatus.userId = uid;
				piccUserOnlineStatus.isOnline = "0";

				piccUserOnlineStatus.updateTime = dbTimeService.getDbTimeStamp();
				if (piccUserOnlineStatusService.isExist(uid) == true) {
					piccUserOnlineStatusService.updateStatus(piccUserOnlineStatus);
				}
				stsMap.put("sts", "0");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			} else {
				stsMap.put("sts", "1");
				stsMap.put("msg", "uc 服务器异常 错误码：" + resuelt.code);
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;

			}

		} catch (Exception e) {
			e.printStackTrace();
			stsMap.put("sts", "1");
			stsMap.put("msg", "uc 服务器异常");
			try {
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

		}

		return null;
	}

}